<template>
  <div>
    <el-dialog
      v-model="isShow"
      :title="$demoi18n('panel.fieldSetting.dialogTitle')"
      width="1100px"
      top="8.4vh"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :class="`${customClass} ${visualThemeClassName} ${xvueNameSpace}`"
    >
      <div class="jumpurl-setting-main">
        <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" />
        <el-form
          ref="form"
          v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
          class="form"
          label-position="right"
          :model="form"
          label-width="85px"
        >
          <template v-if="isExtraTypeSettingShow">
            <div class="field-type-wrapper">
              <el-radio-group
                v-model="fieldSettingType"
                size="default"
              >
                <el-radio-button label="style">{{ $demoi18n('panel.fieldSetting.fieldStyle') }}</el-radio-button>
                <el-radio-button label="jump">{{ $demoi18n('panel.fieldSetting.fieldJump') }}</el-radio-button>
              </el-radio-group>
            </div>
            <AdvanceLinkageEditorMain
              v-show="fieldSettingType === 'jump'"
              ref="mainBox"
              :linkage-datas="linkageDatas"
              :config="form"
            />
            <!-- 百分比配置项 -->
            <div
              v-if="fieldSettingType === 'style' && fieldType === 'percentage'"
              class="percentage-wrapper field-setting-wrapper"
            >
              <VsFormItem :label="$demoi18n('panel.fieldSetting.perStyle')">
                <el-radio-group
                  v-model="form.style.perStyle"
                  size="default"
                >
                  <el-radio label="progressAndPercentage">{{
                    $demoi18n('panel.fieldSetting.progressAndPercentage')
                  }}</el-radio>
                  <el-radio label="progress">{{ $demoi18n('panel.fieldSetting.progress') }}</el-radio>
                  <el-radio label="percentage">{{ $demoi18n('panel.fieldSetting.percentage') }}</el-radio>
                </el-radio-group>
              </VsFormItem>
              <VsFormItem :label="$demoi18n('panel.fieldSetting.basis')">
                <el-radio-group
                  v-model="form.style.basis"
                  size="default"
                >
                  <el-radio label="max100">{{ $demoi18n('panel.fieldSetting.max100') }}</el-radio>
                  <el-radio label="maxTagetNum">{{ $demoi18n('panel.fieldSetting.maxTagetNum') }} </el-radio>
                </el-radio-group>
              </VsFormItem>
              <VsFormItem
                v-if="form.style.basis === 'maxTagetNum'"
                :label="$demoi18n('panel.fieldSetting.targetNum')"
              >
                <el-input-number
                  v-model="form.style.targetNum"
                  size="default"
                  :precision="0"
                  :controls="false"
                ></el-input-number>
              </VsFormItem>
              <VsFormItem
                v-if="form.style.basis === 'maxTagetNum'"
                :label="$demoi18n('panel.fieldSetting.percentDecimalCount')"
              >
                <el-input-number
                  v-model="form.style.percentDecimalCount"
                  size="default"
                  :precision="0"
                  :controls="false"
                ></el-input-number>
              </VsFormItem>
              <VsFormItem
                v-if="form.style.perStyle === 'progressAndPercentage'"
                prop="valueWidth"
                :label="$demoi18n('panel.lable.rightWidth')"
              >
                <el-input-number
                  v-model="form.style.valueWidth"
                  size="default"
                  :min="20"
                  :max="400"
                  :controls="false"
                ></el-input-number>
              </VsFormItem>
              <VsFormItem
                :label="$demoi18n('panel.fieldSetting.progressColor')"
                class="base-option"
              >
                <ColorPicker v-model:value="form.style.color" />
              </VsFormItem>
            </div>
            <!-- 状态配置项 -->
            <div
              v-if="fieldSettingType === 'style' && fieldType === 'status'"
              class="percentage-wrapper field-setting-wrapper"
            >
              <VsFormItem :label="$demoi18n('panel.fieldSetting.perStyle')">
                <el-radio-group
                  v-model="form.style.statusStyle"
                  size="default"
                >
                  <el-radio label="status">{{ $demoi18n('panel.fieldSetting.status') }}</el-radio>
                  <el-radio label="statusAndIcon">{{ $demoi18n('panel.fieldSetting.statusAndIcon') }}</el-radio>
                  <el-radio label="icon">{{ $demoi18n('panel.fieldSetting.icon') }}</el-radio>
                </el-radio-group>
              </VsFormItem>
              <el-button
                class="btn-sure button-sure"
                size="default"
                icon="CirclePlus"
                @click.stop="addNewRow()"
              >{{ $demoi18n('btn.add') }}</el-button>
              <el-table
                class="config-panel-table mapping-table"
                :data="form.style.statusTable"
                :row-style="{ height: '25px' }"
                :header-row-style="{ height: '25px' }"
                max-height="235"
                :header-cell-style="{ lineHeight: '15px' }"
              >
                <el-table-column
                  type="index"
                  :label="$demoi18n('word.serialNumber')"
                  :width="100"
                ></el-table-column>
                <el-table-column
                  :render-header="renderTableHeader"
                  prop="name"
                  :label="$demoi18n('word.name')"
                  :min-width="110"
                >
                  <template #default="scope">
                    <VsFormItem
                      :prop="`style.statusTable[${scope.$index}].name`"
                      :rules="
                        generateRules({
                          required: false,
                        })
                      "
                    >
                      <ValueInputer
                        v-model:value="scope.row.statusField"
                        :enum-values="valueList"
                      />
                    </VsFormItem>
                  </template>
                </el-table-column>
                <el-table-column
                  :render-header="renderTableHeader"
                  prop="icon"
                  :label="$demoi18n('word.icon')"
                  width="100"
                >
                  <template #default="scope">
                    <IconEditor
                      :icon="scope.row.icon"
                      :has-sync="true"
                      @save="saveIcon($event, scope.row)"
                      @delete="deleteIcon($event, scope.row)"
                      @sync="syncIcons($event, form.style.statusTable)"
                    />
                  </template>
                </el-table-column>
                <el-table-column width="80">
                  <template #default="scope">
                    <el-button
                      icon="Delete"
                      :link="true"
                      type="primary"
                      @click.stop="deleteCurRow(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
          <template v-else>
            <AdvanceLinkageEditorMain
              ref="mainBox"
              :linkage-datas="linkageDatas"
              :config="form"
            />
          </template>
          <div class="action-button-group">
            <el-button
              class="button-sure"
              size="small"
              type="primary"
              @click="handleSave()"
            >{{
              $demoi18n('btn.confirm')
            }}</el-button>
            <el-button
              class="button-cancel"
              size="small"
              @click="cancel()"
            >{{ $demoi18n('btn.close') }}</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="jsx">
import AdvanceLinkageEditorMain from '@/components/common/advanced-linkage/advanced-linkage-editor-main.vue';
import ColorPicker from '@/components/common/color-picker/color-picker.vue';
import IconEditor from '@/components/common/icon/icon-editor.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import imgUploadBase from '@/mixin/img-upload-base.js';
import { generateRules, genRequireRule } from '@/utils/rules';
import { clone, validChildForms } from '@/utils/util';
import { mapState } from 'vuex';

export default {
  name: 'JumpUrlSetting',
  components: {
    PanelLabelOverflowTooltip,
    AdvanceLinkageEditorMain,
    ColorPicker,
    IconEditor,
    ValueInputer,
  },
  mixins: [imgUploadBase],
  provide() {
    return {
      addChild: formVm => {
        this.validateForms.push(formVm);
      },
    };
  },
  props: ['config', 'curComp'],
  emits: ['save'],
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      isAurora: this.$platformName === 'Aurora',
      xvueTheme: window._adoPremise.uc.theme,
      customClass: `jumpurl-setting-dialog jumpurl-setting-dialog-${window._adoPremise.uc.theme || 'light'}`,
      isShow: false,
      activeColorRadio: '#2D8CF0', // 单选框选中时的颜色
      form: {},
      fieldType: '',
      index: 0,
      fieldSettingType: 'style',
      linkageDatas: [],
      validateForms: [],
    };
  },
  computed: {
    ...mapState({
      panelApiData: state => state.VisualComponentsModule.panelApiData,
      panelApiTableData: state => state.VisualComponentsModule.panelApiTableData,
    }),
    valueList() {
      let arr = [];
      if (this.curComp === 'table') {
        arr = this.panelApiTableData.map(n => {
          if (n[this.form.field] !== null) {
            return n[this.form.field]?.toString();
          }
          return '';
        });
      } else {
        arr = this.panelApiData.map(n => {
          if (n[this.form.field] !== null) {
            return n[this.form.field]?.toString();
          }
          return '';
        });
      }
      arr = Array.from(new Set(arr));
      const options = arr.map(n => ({ label: n, value: n }));
      return options;
    },
    isExtraTypeSettingShow() {
      return this.fieldType !== 'number' && this.fieldType !== 'string';
    },
  },
  watch: {},
  mounted() {
    if (!this.$refs.form) {
      return;
    }
    this.validateForms.push(this.$refs.form);
  },
  methods: {
    genRequireRule,
    generateRules,
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    openDialog(data, index) {
      const { advancedLinkage, fieldType } = data;

      // 选择对应类型的form样式配置项
      this.form = clone(data);
      this.linkageDatas = JSON.parse(JSON.stringify(advancedLinkage.linkageDatas || []));
      this.fieldType = fieldType;
      this.index = index;
      this.isShow = true;
    },

    cancel() {
      this.isShow = false;
    },
    async handleSave() {
      const errors = await validChildForms(this.validateForms);
      if (errors.length) {
        if (this.isExtraTypeSettingShow) {
          this.fieldSettingType = 'jump';
        }
        return;
      }

      this.saveAdvancedLinkage();
      this.$emit('save', { fieldForm: this.form, index: this.index });
      this.cancel();
    },
    saveAdvancedLinkage() {
      const { advancedLinkage = {} } = this.form;
      advancedLinkage.linkageDatas = this.linkageDatas;
      this.form.advancedLinkage = clone(advancedLinkage);
    },
    addNewRow() {
      const temp = {
        statusField: '',
        icon: '',
        iconSmall: '',
        uploadList: '',
        imgUrl: '',
      };
      this.form.style.statusTable.push(temp);
    },
    deleteCurRow(item) {
      const index = this.form.style.statusTable.indexOf(item);
      this.form.style.statusTable.splice(index, 1);
    },
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
  },
};
</script>

<style lang="less">
@import '../../../common/color-picker-panel.less';
</style>
<style lang="less" scoped>
.jumpurl-setting-dialog {
  .jumpurl-setting-main {
    .form {
      width: 100%;
      .field-type-wrapper {
        margin-bottom: 10px;
      }
      :deep(.el-form-item) {
        .el-form-item__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .base-option {
        :deep(.el-form-item__content) {
          display: flex;
          min-height: 40px;
          align-items: center;
        }
      }
      .is-error {
        margin-bottom: 15px;
      }
      .el-form-item__error {
        top: 100%;
        padding-top: 0;
      }
      .field-setting-wrapper {
        width: 550px;
        :deep(.el-form-item) {
          margin-bottom: 0;
        }
        .mapping-table {
          :deep(.el-form-item) {
            .el-form-item__content {
              margin-left: 0 !important;
              .el-input__icon {
                line-height: 40px;
              }
            }
          }
          .mapping-scope {
            color: #f56c6c;
            margin-right: 4px;
            position: absolute;
            left: -5px;
            top: 25%;
          }
        }
      }
    }
  }

  .action-button-group {
    text-align: right;
    padding-top: 20px;
    .button-sure {
      padding: 9px 35px;
      border-radius: 0;
    }
    .button-cancel {
      padding: 9px 35px;
      border-radius: 0;
    }
  }
}
</style>

<style lang="less">
@font_color_dark: #98cae6;
@borderColor_dark: #116584;
@textColor_dark: #ffffff;
@bgColor_dark: #000c17;
@font_color_active_dark: #00f0ff;
@background_color_dark: #071f30;
.jumpurl-setting-dialog-dark {
  .el-dialog__header {
    background: #183c5a;
    .el-dialog__title {
      color: #fff;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #fff;
      }
    }
  }

  .el-dialog__body {
    background: #0e2b40;

    .el-form-item__label {
      color: @font_color_dark;
    }

    .el-input {
      .el-input__inner {
        border-color: @borderColor_dark;
        color: @textColor_dark;
        background-color: @bgColor_dark;
      }

      .el-input__icon {
        color: @borderColor_dark;
      }
    }

    .el-radio-group {
      .el-radio {
        color: @textColor_dark;

        .el-radio__input {
          .el-radio__inner {
            border-color: @font_color_active_dark;
            background-color: unset;
          }
        }

        .is-checked {
          .el-radio__inner {
            &::after {
              background-color: @font_color_active_dark;
            }
          }
        }

        .el-radio__label {
          color: #fff;
        }
      }
      .is-checked {
        .el-radio__label {
          color: #00f0ff;
        }
      }
    }

    .el-switch__core {
      background-color: #064559;
      border-color: #064559;
    }

    .el-switch.is-checked {
      .el-switch__core {
        background-color: #0eb4c2;
        border-color: #0eb4c2;
      }
    }

    .el-color-picker {
      .el-color-picker__trigger {
        border-color: @borderColor_dark;
      }
    }

    // 表格
    .config-panel-table {
      color: @font_color_dark;
      background-color: @background_color_dark;

      &::before {
        background-color: @background_color_dark;
      }

      .cell {
        padding: 0 3px !important;
      }
      td,
      th {
        padding: 5px 0 !important;
      }

      .el-table__header {
        th {
          background-color: #122b40 !important;
          border-color: #122b40;
          color: @font_color_dark;
        }
      }

      .el-table__body {
        tr {
          td {
            background-color: @background_color_dark;
            border-color: @background_color_dark;

            .icon-library-open {
              background-color: unset;
              border-color: #0eb4c2;
            }
          }
        }
      }

      .el-table__empty-block {
        background-color: #093758;

        .el-table__empty-text {
          color: @font_color_active_dark;
        }
      }
    }

    .button-sure {
      background-color: #0eb4c2;
      border-color: #0eb4c2;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }

    .button-cancel {
      background-color: #064559;
      border-color: #064559;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }
  }
}
</style>
